package com.zhugang.week13.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: preorderTraversal2
 * @author: chanzhugang
 * @create: 2022/12/13 10:54
 */
public class PreorderTraversal2 {

    /**
     * 144 二叉树的前序遍历
     * https://leetcode.cn/problems/binary-tree-preorder-traversal/
     * <p>
     * 前中后序遍历本质都是深度优先搜索
     *
     * @param root
     * @return
     */
    List<Integer> result = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        // 递归标准模版
        preorder(root);
        return result;
    }

    private void preorder(TreeNode root) {
        if (root == null) {
            return;
        }
        result.add(root.val);
        preorder(root.left);
        preorder(root.right);
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}